import 'dart:async';

import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/material.dart';
import 'package:flutter_changdian_football/api/api_response.dart';
import 'package:flutter_changdian_football/api/req/user/req_user.dart';
import 'package:flutter_changdian_football/global.dart';
import 'package:flutter_changdian_football/pages/mine/user_store.dart';
import 'package:flutter_changdian_football/routers/app_routes.dart';
import 'package:flutter_changdian_football/utils/custom_constant.dart';
import 'package:flutter_changdian_football/utils/event/custom_event_util.dart';
import 'package:flutter_changdian_football/utils/regex/regex_util.dart';
import 'package:flutter_changdian_football/widget/toast/custom_toast.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {

  TextEditingController phoneController = TextEditingController();
  TextEditingController codeController = TextEditingController();

  bool isAgree = false;
  changeAgree() {
    isAgree = !isAgree;
    changeSubmit();
  }

  bool isSubmit = false;
  changeSubmit() {
    if (phoneController.text.trim() == '' || codeController.text.trim() == '' || isAgree == false) {
      isSubmit = false;
    } else {
      isSubmit = true;
    }
    update();
  }

  login() async {
    if (isSubmit == false) {
      return ;
    }
    if (!CustomRegexUtil.isMobileExact(phoneController.text.trim())) {
      CustomToast.showTextToast('请输入正确的手机号');
      return ;
    }

    if (codeController.text.trim().length < 6) {
      CustomToast.showTextToast('请输入正确的验证码');
      return ;
    }

    try {
      FocusScope.of(Get.context!).requestFocus(FocusNode());
      EasyLoading.show();
      var resp = await ReqUser.loginByVerificationCode(telephone: phoneController.text.trim(), captcha: codeController.text.trim());
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          Global.accessToken = resp.data['data']['token'];
          SpUtil.putString('Authorization', Global.accessToken);

          eventBus.fire(const BottomNavigationBarEvent(CustomConstant.EVENT_REFRESH));

          Get.until((route) => Get.currentRoute == AppRoutes.main);

          if (resp.data['data']['isOldUser'] == false) {
            Get.toNamed(AppRoutes.personalInfo);
          }
        } else {
          CustomToast.showTextToast('${resp.data['msg']}');
        }
      } else {
        CustomToast.showTextToast('${resp.data?['msg'] ?? '系统繁忙，请稍后再试'}');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试');
    } finally {
      EasyLoading.dismiss();
    }
  }


  Timer? timer;
  int timeCount = 60;
  String autoCodeText = '获取验证码';
  /// 是否发送验证码
  bool isSendCode = false;

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }


  /// 验证码倒计时
  void startTimer() {
    timer?.cancel();
    timeCount = 60;
    isSendCode = true;
    autoCodeText = "$timeCount秒";
    update();
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      if (timeCount <= 1) {
        autoCodeText = '重新获取';
        timer.cancel();
        timeCount = 60;
        isSendCode = false;
        update();
      } else {
        timeCount -= 1;
        autoCodeText = "$timeCount秒";
        isSendCode = true;
        update();
      }
    });
  }

  // 获取验证吗
  sendCode() async {
    if (isSendCode == true) {
      return ;
    }
    if (!CustomRegexUtil.isMobileExact(phoneController.text.trim())) {
      CustomToast.showTextToast('请输入正确的手机号');
      return ;
    }
    try {
      EasyLoading.show();
      var resp = await ReqUser.sendVerificationCode(type: CustomConstant.CODE_REGISTER, telephone: phoneController.text);
    
      if (resp.status == Status.completed) {
        if (resp.data['code'] == '200') {
          EasyLoading.showToast('短信验证码已发送至您的手机，请注意查收～');
          startTimer();
        } else {
          CustomToast.showTextToast('${resp.data['msg']}');
        }
      } else {
        CustomToast.showTextToast('${resp.data?['msg'] ?? '系统繁忙，请稍后再试'}');
      }
    } catch (e) {
      CustomToast.showTextToast('系统繁忙，请稍后再试');
    } finally {
      EasyLoading.dismiss();
    }
  }

}